package com.cabal.module;

import com.cabal.auth.dao.CabalAuthMapper;
import com.cabal.auth.dao.CabalGatewayGameConfigMapper;
import com.cabal.auth.entity.CabalGatewayGameConfig;
import com.cabal.common.constants.SystemConstants;
import com.cabal.config.DynamicDataSourceContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Set;

@Slf4j
@Component
public class CabalCommandLineRunnerImpl implements CommandLineRunner {

    /*@Value("${command.init:false}")
    private Boolean initState;*/

    private static final String CABAL_ONLINE_CODE = "CABAL_ONLINE_CODE_";

    private static String LOGIN_NOTICE_KEY = "LOGIN_NOTICE_KEY_";

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private CabalAuthMapper cabalAuthMapper;

    @Resource
    private CabalGatewayGameConfigMapper cabalGatewayGameConfigMapper;

    @Override
    public void run(String... args) throws Exception {
       boolean initState = false;
       try {
           DynamicDataSourceContextHolder.setContextKey(SystemConstants.DS_KEY_CABALMALL);
           CabalGatewayGameConfig cabalGatewayGameConfig = cabalGatewayGameConfigMapper.selectById(1);
           DynamicDataSourceContextHolder.removeContextKey();
           if(cabalGatewayGameConfig != null) {
               Integer commandInit = cabalGatewayGameConfig.getCommandInit();
               if(commandInit == 1) {
                   initState = true;
               }
           }
       } catch (Exception e) {
           log.error("初始化异常", e);
       }

       if(initState) {
            log.info("初始化数据...");
            // 1、清理redis计算泡点的KEY
            Set<String> allKeys = stringRedisTemplate.keys(CABAL_ONLINE_CODE + "*");
            for(String key : allKeys) {
                log.info("-----------清理key------------" + key);
                stringRedisTemplate.delete(key);
            }

            Set<String> allKeys2 = stringRedisTemplate.keys(LOGIN_NOTICE_KEY + "*");
            for(String key : allKeys2) {
                log.info("-----------清理key------------" + key);
                stringRedisTemplate.delete(key);
            }

            // 2、修改在线登录账号状态角色在线状态
            cabalAuthMapper.initOnlineUserState();

            cabalAuthMapper.initOnlineCharacterState();
       } else {
            log.info("不初始化数据...");
       }

    }
}
